/*
* Loader v1.1 (jan 16, 2012)
* Copyright 2011 group94 - http://www.group94.com
* Unauthorised use, copying and/or redistributing is strictly prohibited.
*
* USAGE:
    var loader = new Loader();
	loader.onComplete = function($response){
		$json = JSON.parse($response)
	}
	loader.onError = function($error){
		alert("onError(): " + $error)
	}
	loader.load(PHP+'api.php?json='+encodeURIComponent(JSON.stringify(json)));
*/

function Loader(){
	var ths = this;
	ths.request;
	ths.method = "GET";		//can be set to: loader.method = "POST"
	
	ths.load = function($url){
		try{	ths.request = new XMLHttpRequest();	}catch($e){}	// Firefox/Safari
		if(!ths.request)	try{	ths.request = new ActiveXObject("Microsoft.XMLHTTP")	}catch($e){}	// IE
		if(!ths.request)	try{	ths.request = new ActiveXObject("Msxml2.XMLHTTP")		}catch($e){}
		if(!ths.request)	try{	ths.request = new ActiveXObject("Msxml3.XMLHTTP")		}catch($e){}
		
		if(!ths.request){
			throw new Error("Error: Unable to create XMLHttpRequest.");
			return;
		}
		ths.request.open(ths.method, $url, true);
		//ths.request.setRequestHeader('User-Agent','XMLHTTP/1.0');
		if(ths.method.toLowerCase()=="post")	ths.request.setRequestHeader('Content-type','application/x-www-form-urlencoded');
		
		ths.request.onreadystatechange = function(){
			// wait for it..
			if(ths.request.readyState != 4)	return;
			
			// on error:
			if(ths.request.status!=200 && ths.request.status!=304){
				if(ths.onError)	ths.onError(ths.request.status)
				return;
			}
			
			// on ok:
			if(ths.onComplete){
				ths.onComplete(ths.request.responseText);
				ths.onComplete = null;
			}
		}
		
		ths.request.send($url);
	}
	ths.cancel = function(){
		if(ths.request) ths.request.abort();	
	}
}